package com.sfac.springboot.filter;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter
public class ParamFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        LOGGER.debug("=== init filter=====");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        /*HttpServletRequest req = (HttpServletRequest) request;
        req.getParameterMap();*/

        LOGGER.debug("=== do filter=====");
        //将ServletRequest 等转化为 HttpServletRequest 等
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //因为 HttpServletRequest 不能直接操作 parameterMap，所以构建Wrapper对象来操作
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req){


        //重写wrapper对象的getParameter 方法，替换掉脏字符串
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);

                return value.replaceAll("fuck","***");
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values == null) {
                    return new String[]{};
                }
                return Arrays.asList(values)
                        .stream()
                        .map(item -> item.replaceAll("fuck","***"))
                        .toArray(String[]::new);
            }
        };

        //将wrapper和 response 对象交出去
        chain.doFilter(wrapper,response);
    }

    @Override
    public void destroy() {

        LOGGER.debug("=== destroy filter=====");
    }
}
